import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, Alert, Dimensions
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { RangTime } from '../../../component/common/RangTime.js';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { NewAccountHome } from '../../../components/common/newAccountHome';

const scale = GLOBAL.SCALE;
const TAB_LIST = [
	{
		name: '采购合同',
		type: 'P', // TODO
	}, {
		name: '销售合同',
		type: 'S', // TODO
	}
]
const modalPicDelCfg = {
	visible: false,
	urls: [],
	picPress: () => { },
}
export class preReviewList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '合同预审',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			status: 'data',
			companyIndex: 0,
			// showTimeModal: false, // 时间选择
			refreshIcon: false, // 下拉刷新图标
			listData: [], // 列表数据
			saleCount: 0,
			purchaseCount: 0,
			refuseModalVisible: false,
			alertShow: false,
			options: [],
			choice: {}
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数

		this.pageParams = { // TODO
			pageNo: 1,
			pageSize: 10,
			orderType: 'P'
		}
	}

	async componentWillMount() {
		await this.getRecord();
		await this.initPage();
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let { options } = this.state
		this.pageParams.corpId = options[this.state.companyIndex].corpId
		let res = await HTTP.POST(API_GENERATE(API.PRE_TAST_LIST), this.pageParams); // TODO
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
				choice: options[this.state.companyIndex] || {},
				saleCount: options[this.state.companyIndex].saleTaskCnt || 0,
				purchaseCount: options[this.state.companyIndex].purchaceTaskCnt || 0,
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error',
			})
		}
	}

	async _getPdfPreview(fileId) {
		if (!fileId) {
			return
		}
		else {
			this.props.navigation.navigate('ContractPdfPage', {
				finalFileId: fileId,
				title: '附件信息'
			})
		}
	}

	// 获取列表数量
	async getRecord() {
		const res = await HTTP.POST(API_GENERATE(API.UN_FLOW_CNT), { processDefinitionKey: 'APP_ORDER_PRE_AUDIT' });
		res.map((item) => {
			item.rowCount = item.taskCnt
		})
		this.setState({
			options: res || [],
			choice: res[0],
		})
	}

	// 刷新页面
	reloadPage = async () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		await this.getRecord()
		await this.initPage();
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	// tab切换
	changeTab = (item) => {
		this.pageParams.orderType = item.type;
		this.reloadPage();
	}

	async _audit() {
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(API.PRE_TAST_AUDIT), {
			businessKey: this.businessKey,
			auditResult: this.isAgreed,
			remark: this.remark, // 填写
			formKey: "PRE_AUDIT"
		});
		this.setState({ loaded: false });
		console.log('responseData', responseData)
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => {
				this.requesting = false;
				this.getRecord();
				this.initPage();
			})
		} else {
			this.requesting = false;
		}
	}

	_pass() {
		this.isAgreed = 1;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	_refuse() {
		this.isAgreed = 0;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	// tab
	_renderTabWrap() {
		const { saleCount, purchaseCount } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					TAB_LIST.map((item, index) => {
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(item) }} key={index} style={[styles.tabItem, this.pageParams.orderType == item.type ? { backgroundColor: style.color.themeColor } : { backgroundColor: 'transparent' }]}>
								<Text style={[styles.tabText, this.pageParams.orderType == item.type ? { color: '#fff' } : { color: style.color.themeColor }]}>{item.name}</Text>
								{(item.type == 'P' && purchaseCount) || (item.type != 'P' && saleCount) ?
									<View style={[styles.numPoint, this.pageParams.orderType == item.type ? { backgroundColor: '#fff' } : { backgroundColor: 'red' }]}></View> : null
								}
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	// 列表
	_renderListItem = (data) => {
		const { companyName, signTime, outContractNo, orderId, contractStandard,
			bizStaffName, bizTeamName, documentaryByName, organName, finalFileId, tradeType, bizMode, createTime, creditLevel } = data.item;
		return (
			<TouchableOpacity activeOpacity={1} onPress={() => {
				this.props.navigation.navigate('preReviewDetail', {
					orderId: orderId,
					itemData: data.item,
					callback: () => this.reloadPage()
				})
			}} style={{ marginBottom: 18 * scale }}>
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
					<Text style={styles.titleText}>{companyName || '-'} ({creditLevel}级)</Text>
					<Text style={styles.titleText}>{(createTime || '-').substring(0, 16)}</Text>
				</View>
				<View style={{ backgroundColor: '#fff', borderRadius: 4 * scale }}>
					<View style={styles.billNumWrap}>
						<Text style={{ paddingVertical: 10 * scale, fontWeight: '600', fontSize: 12 * scale }}>{orderId} </Text>
						<View style={[styles.orderTypes, { backgroundColor: '#0086ff' }]}>
							<Text style={{ fontSize: 11, color: '#FFF' }}>{tradeType === 'I' ? '内' : '外'}</Text>
						</View>
						<View style={[styles.orderTypes, { backgroundColor: '#c30405' }]}>
							<Text style={{ fontSize: 11, color: '#FFF' }}>{bizMode === '1' ? '闭' : '敞'}</Text>
						</View>
					</View>
					<View style={styles.billInfoWrap}>
						<View style={{ flexDirection: 'row', alignItems: 'center' }}>
							<Text style={styles.commonTitle}>合同标准</Text>
							<Text style={styles.commonTitle}>外部合同号</Text>
							<Text style={styles.commonTitle}>合同附件</Text>
						</View>
						<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
							<Text style={styles.commonText}>{contractStandard == '1' ? '标准合同' : '外部合同'}</Text>
							<Text style={styles.commonText}>{outContractNo || '-'}</Text>
							<TouchableOpacity style={{ flex: 1 }} onPress={() => { this._getPdfPreview(finalFileId) }}>
								<Text style={[styles.commonText1, finalFileId ? { color: '#0091FF' } : { color: '#000' }]}>{finalFileId ? '【查看附件】' : '-'}</Text>
							</TouchableOpacity>
						</View>
					</View>

					<View style={styles.billInfoWrap}>
						<View style={{ flexDirection: 'row' }}>
							<View style={{ flex: 1 }}>
								<Text style={[styles.commonTitle]}>签约日期</Text>
							</View>
							<View style={{ flex: 1 }}>
								<Text style={[styles.commonTitle]}>业务&订单部门</Text>
							</View>
							<View style={{ flex: 1 }}>
								<Text style={styles.commonTitle}>制单人</Text>
							</View>
						</View>
						<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
							<Text style={styles.commonText}>{signTime ? signTime.substring(0, 10) : null}</Text>
							<Text style={styles.commonText}>{bizStaffName + '(' + bizTeamName + '/' + organName + ')'}</Text>
							<Text style={styles.commonText}>{documentaryByName || '-'}</Text>
						</View>
					</View>

					<View style={styles.buttonBox}>
						<TouchableOpacity style={styles.buttonPass} activeOpacity={1} onPress={() => {
							this.businessKey = orderId;
							this._pass();
						}}>
							<Text style={styles.buttonPassText}>通过</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.buttonRefuse} activeOpacity={1} onPress={() => {
							this.businessKey = orderId;
							this._refuse();
						}}>
							<Text style={styles.buttonRefuseText}>驳回</Text>
						</TouchableOpacity>
					</View>
				</View>
			</TouchableOpacity>
		)
	}

	render() {
		let { status, listData, refreshIcon, alertShow, choice, options } = this.state;
		return (
			<View style={styles.container}>
				{options.length > 1 ?
					<NewAccountHome
						fn={(val) => { this.setState({ companyIndex: val }, () => { this.pageParams.pageNo = '1'; this.initPage(); }) }}
						options={options}
						choice={choice} />
					: null}
				{this._renderTabWrap()}
				{
					status == 'data' ? (
						<View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale, paddingLeft: 16 * scale, paddingRight: 16 * scale }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
				}
				<ApproveRefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._audit();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingLeft: 17 * scale,
		paddingRight: 17 * scale,
		paddingBottom: 20 * scale,
	},
	filterWrap: {
		marginTop: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		position: 'relative',
	},
	dateWrap: {
		width: 110 * scale,
		height: 36 * scale,
		paddingLeft: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255 ,255 , 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		paddingRight: 14 * scale,
	},
	dateImgWrap: {
		width: 36 * scale,
		height: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255, 255, 255, .08)',
		position: 'absolute',
		top: 0,
		left: 0,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	dateText: {
		fontSize: 10 * scale,
		color: '#fff',
		opacity: .8,
		textAlign: 'center'
	},
	dateLine: {
		width: 7 * scale,
		height: 1 * scale,
		backgroundColor: 'rgba(255, 255, 255, .36)',
		marginTop: 3 * scale,
		marginBottom: 3 * scale,
	},
	tabWrap: {
		backgroundColor: style.color.bgGray,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 10,
		paddingBottom: 10
	},
	tabItem: {
		// flex:1,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginHorizontal: 10,
		borderWidth: 1,
		borderRadius: 20,
		borderColor: style.color.themeColor
	},
	tabText: {
		color: '#fff'
	},
	numPoint: { backgroundColor: '#fff', width: 5, height: 5, position: 'absolute', borderRadius: 16, right: 10, top: 5 },
	billNumWrap: {
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		// paddingHorizontal: 16 * scale,
	},
	billInfoWrap: {
		flexDirection: 'column',
		alignItems: 'flex-start',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 24 * scale,
	},
	commonTitle: {
		flex: 1,
		color: '#030303',
		fontSize: 12 * scale,
		minWidth: 64 * scale,
		paddingHorizontal: 5 * scale
	},
	commonText: {
		flex: 1,
		fontSize: 13 * scale,
		color: '#0C0C0D',
		fontWeight: '700',
		paddingTop: 8 * scale,
		paddingHorizontal: 5 * scale
	},
	commonText1: {
		fontSize: 13 * scale,
		color: '#0C0C0D',
		fontWeight: '700',
		paddingTop: 8 * scale,
		paddingBottom: 10 * scale
	},
	buttonPass: {
		width: 68 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		marginRight: 14 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 68 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	titleText: {
		color: '#848A96',
		marginBottom: 6 * scale,
		fontSize: 12 * scale
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		marginTop: 18 * scale
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	orderTypes: {
		borderRadius: 2,
		paddingHorizontal: 2,
		paddingVertical: 2,
		marginLeft: 5
	},
})